package com.gxcommunication.sociallearn.widget;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ProgressBar;

import com.gxcommunication.sociallearn.R;
import com.gxcommunication.sociallearn.base.BaseActivity;
import com.gxcommunication.sociallearn.http.Api.BaseApi;
import com.gxcommunication.sociallearn.http.service.ApiStore;
import com.gxcommunication.sociallearn.utils.FileUtils;
import com.gxcommunication.sociallearn.utils.GsonUtlils;
import com.gxcommunication.sociallearn.utils.ImageManager;
import com.gxcommunication.sociallearn.utils.LogHelper;
import com.gxcommunication.sociallearn.widget.PhotoView.PhotoView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


/**
 * create by hxc
 * 描述：图片查看类  单图片
 */
public class ImagePreviewActivity extends BaseActivity {
    public static final String INTENT_KEY_IMAGE_PATH = "image_path";
    public static final String  INTENT_KEY_IS_LOCAL = "is_local";
    private ProgressBar progressBar;
    private PhotoView imageView;

    public  String ImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ShengQian/image/"; // SD卡主目录

    @Override
    protected int getLayoutId() {
        return R.layout.activity_image_preview;
    }

    @Override
    protected void init() {
        initHeadActionBar();
        imageView = (PhotoView) this.findViewById(R.id.image_preview_iv);
        progressBar = (ProgressBar) this
                .findViewById(R.id.image_preview_progressBar);
        getdata();

        findViewById(R.id.downloadIv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileUtils.createOrExistsDir(ImagePath);
                if (isEmptyStringIntent(INTENT_KEY_IMAGE_PATH)){
                    String path = getIntentStringValue(INTENT_KEY_IMAGE_PATH);

                    String name  = FileUtils.getFileName(path);

                    downloadFile(path,ImagePath,name);

                }

            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void getdata() {
        String path = getIntentStringValue(INTENT_KEY_IMAGE_PATH);

        ImageManager.getManager(this).loadUrlFitImage(path,imageView);
    }

    @Override
    public void initHeadActionBar() {
        super.initHeadActionBar();
        head_action_title.setText("图片浏览");
    }


    /**
     * 指定线程下载文件(异步)，非阻塞式下载
     *
     * @param url       图片url
     * @param savePatch 下载文件保存目录
     * @param fileName  文件名称
     */
    public void downloadFile(String url, final String savePatch, final String fileName) {
        LogHelper.e("============" + url);
        if (url.contains(Environment.getExternalStorageDirectory().getAbsolutePath())){//本地文件
            showToast("文件已保存, 文件路径：" + url);
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, url);
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = ImagePreviewActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            // 发送广播，通知刷新图库的显示
            ImagePreviewActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            ImagePreviewActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + url)));
            return;
        }

        if (!url.contains("http")){
            showToast("文件格式错误, 文件路径：" + url);
            return;
        }

        showProgress();
        ApiStore.createApi(BaseApi.class)
                .downloadImg(url)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .map(new Function<ResponseBody, String>() {

                    @Override
                    public String apply(ResponseBody responseBody) throws Exception {
                        Bitmap bitmap = null;
                        String savePath = savePatch + fileName;
                        byte[] bys;
                        try {
                            bys = responseBody.bytes();
                            bitmap = BitmapFactory.decodeByteArray(bys, 0, bys.length);

                            File file = new File(savePath);
                            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                            bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();

                        } catch (IOException e) {
                            e.printStackTrace();
                            return "";
                        }

                        if (bitmap != null) {
                            bitmap.recycle();
                        }
                        return savePath;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<String>() {
                    @Override
                    public void onNext(String responseBody) {
                        hideProgress();
                        LogHelper.e("============" + responseBody);
                        if (responseBody.isEmpty()){

                            showDiglog("下载图片失败，是否重新获取？", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (isEmptyStringIntent(INTENT_KEY_IMAGE_PATH)) {
                                        String path = getIntentStringValue(INTENT_KEY_IMAGE_PATH);
                                        String name = System.currentTimeMillis() + ".jpg";
                                        downloadFile(path, ImagePath, name);
                                    }
                                }
                            });

                            return;
                        }
                        showToast("下载成功, 文件路径：" + ImagePath);
                        try {

                            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                            File f = new File(responseBody);
                            Uri contentUri = Uri.fromFile(f);
                            mediaScanIntent.setData(contentUri);
                            ImagePreviewActivity.this.sendBroadcast(mediaScanIntent);
                            ImagePreviewActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + responseBody)));
                        } catch (Exception e) {
                            LogHelper.e(GsonUtlils.objectToJson(e));
                            //方式一 插入图片到相册 缺点是相册和文件夹会有两张同样的照片
//                            MediaStore.Images.Media.insertImage(ImagePreviewActivity.this.getContentResolver(), responseBody,fileName , null);
                            //方式二 提示ContentValues 提示系统更新下载的图片
                            ContentValues values = new ContentValues();
                            values.put(MediaStore.Images.Media.DATA, responseBody);
                            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                            Uri uri = ImagePreviewActivity.this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                            // 发送广播，通知刷新图库的显示
                            ImagePreviewActivity.this.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        showToast("未知错误，下载失败");
                        //你的处理
                        LogHelper.e("onError" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //你的处理
                    }
                });
    }

}
